package com.spsoft.core.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @description: 导出  导入
 * @author: YYQ
 * @create: 2021-05-21 20:49
 **/
public class ExcelUtils {


    /**
     * 导出公共方法
     * @param  list 导出的数据  head 导出模板类  filename 导出名称(文件名称前端定义好）或sheetname
     * @return excel 文件
     **/
    public static void exportExcel(List list, Class head, String fileName, HttpServletResponse response) throws IOException {
        String str = fileName + ".xlsx";
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(str, "UTF-8"));
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        EasyExcel.write(response.getOutputStream(), head)
                .sheet(fileName)
                .doWrite(list);
    }

    /**
     * 使用系统模板导出Excel公共方法
     * @param list 导出数据集合
     * @param fileName 导出文件名
     * @param response 响应对象
     * @param inputStream 模板文件流
     * @throws IOException
     */
    public static void exportExcelWithTemplate(List list, String fileName, HttpServletResponse response, InputStream inputStream) throws IOException {
        fileName = fileName + ".xlsx";
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 创建ExcelWriter实例，写入到指定模板
        ExcelWriter writer = EasyExcel.write(response.getOutputStream()).withTemplate(inputStream).build();
        // 开启填充换行
        FillConfig fillConfig = FillConfig.builder().forceNewRow(true).build();
        // sheet页
        WriteSheet sheet = EasyExcel.writerSheet().build();
        // 执行填充操作
        writer.fill(list, fillConfig, sheet);
        // 结束
        writer.finish();
    }


    /**
     * 导出带有下拉框的数据模板
     *
     * @param list        列表
     * @param head        头
     * @param fileName    文件名称
     * @param response    响应
     * @param dropDownMap 下拉图
     * @author fuqiyun
     * @date 2023-08-18 14:22:21
     */
    public static void exportPullDownExcel(List list,
                                           Class head,
                                           String fileName,
                                           HttpServletResponse response,
                                 Map<Integer,String[]> dropDownMap) throws IOException {
        String str = fileName + ".xlsx";
        String fileNames = new String(str.getBytes(), StandardCharsets.ISO_8859_1);
        response.setHeader("Content-disposition", "attachment;filename=" + fileNames);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        EasyExcel.write(response.getOutputStream(), head)
                .registerWriteHandler(new TitleHandler(dropDownMap))
                .sheet(fileName)
                .doWrite(list);
    }


    /**
     * 导出Excel并在最上方添加自定义内容
     * @param data 数据
     * @param head 表头
     * @param fileName 文件名
     * @param response HttpServletResponse
     * @param title 自定义内容
     * @throws IOException IO异常
     */
    public static <T> void writeExcelWithCustomTitle(List<T> data, List<List<String>> head, String fileName,
                                                     HttpServletResponse response, String title) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "utf-8"));

        ServletOutputStream outputStream = response.getOutputStream();

        // 创建ExcelWriter对象
        ExcelWriter excelWriter = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX, true);

        // 添加自定义内容
        List<List<String>> customTitleList = new ArrayList<>();
        customTitleList.add(Collections.singletonList(title));
        excelWriter.write(customTitleList, writeSheet(0, head));

        // 添加表头和数据内容
        excelWriter.write(data, writeSheet(0, head));

        // 结束写入
        excelWriter.finish();
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 创建表格的写入配置
     * @param sheetNo sheet编号，从0开始
     * @param head 表头
     * @return WriteSheet
     */
    private static WriteSheet writeSheet(int sheetNo, List<List<String>> head) {
        return EasyExcel.writerSheet(sheetNo, "Sheet" + (sheetNo + 1)).head(head).build();
    }

    /**
     * 创建自定义内容的写入配置
     * @param title 自定义内容
     * @return WriteSheet
     */
    private static WriteSheet createCustomTitle(String title) {
        WriteSheet sheet = new WriteSheet();
        sheet.setSheetName("Sheet1");
        sheet.setRelativeHeadRowIndex(-1);
        List<List<String>> list = new ArrayList<>();
        list.add(Collections.singletonList(title));
        sheet.setHead(list);
        return sheet;
    }
}
